import os
import json
import dbAccess
import jsonConverter
from UserDb import UserDb
from CatalogDb import CatalogDb
from AccountDb import AccountDb
import string
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import memcache
import cgi
import logging


def doDispatcher(page):
     if(isInited() and isLogined()):
        theUser = dbAccess.getUserById(memcache.get('userId'))
        result = {
            'target':'main',
            'nickName':theUser.userNickname,
            'password':theUser.userPassword,
            'name':theUser.userName
        }
     elif(isInited()):
        result = {
            'target':'login', 
           }
     else:
        result = {
            'target':'init',
           }
     logging.info('service.doDispatcher:%s' % result['target'])
     page.response.out.write(json.write(result))

def doLogout(page):
    memcache.delete('userId')
    page.response.out.write("ok")
         
def doClearUser(page):
    dbAccess.clearUser()
    dbAccess.clearCatalog()
    if(isInited()):
        rs = '1'
    else:
        rs = '0'
    page.response.headers['Content-Type'] = 'text/plain'
    page.response.out.write(rs)

def doLogin(page):
    userName = page.request.get('name')
    password = page.request.get('password')
    theUser = dbAccess.getUserWhenLogin(userName,password)
    
    if(theUser):
          logging.info('login success')
          memcache.add('userId',theUser.userId)
          result = {
            'message':'success',
            'nickName':theUser.userNickname,
            'password':theUser.userPassword,
            'name':theUser.userName
            }
    else:
       result = {
            'message':'failure'
            }

    page.response.out.write(json.write(result))
        
    
def doInit(page):
    logging.info('doInit')
    userNickname = page.request.get('userNickname')
    if userNickname == '':
        userNickname = page.request.get('userName') 
    logging.info('userNickname'+userNickname)
    userDb = UserDb(
            userId = 1,
            userName = page.request.get('userName'),
            userNickname = userNickname,
            userPassword = page.request.get('userPassword'))
    userDb.put()

    rootCatalog = CatalogDb(catalogName='SelfPassRoot',catalogParent=None)
    rootCatalog.put()

    if(dbAccess.getUser()):
       message = 'success'
       result = {
            'message':message
            }
    else:
       result = {
            'message':'failure'
            }

    page.response.out.write(json.write(result))
 
def isInited():
    if(dbAccess.getUser()):
        return True
    else:
        return False

def isLogined():
    logging.info('isLogined')
    if(memcache.get('userId')):
        return True
    else:
        return False  
    
def showCatalogTree (page):
    catalogList = dbAccess.getAllCatalog()
    result = jsonConverter.convertCatalogList(catalogList)
    page.response.out.write(json.write(result))
 
def showAccountList(page):
    catalogKeyId = page.request.get('catalogId')
    accountList = dbAccess.getAccountsByCatalog(dbAccess.getCatalog(int(catalogKeyId)));
    result = jsonConverter.convertAccountList(accountList)

    page.response.out.write(json.write(result))

def showAccount(page):
    accoutKeyId = page.request.get('key')
    account = dbAccess.getAccount(int(accoutKeyId))

    result = {
          'key': account.key().id(),
          'name': account.accountName,
          'accountId': account.accountId,
          'password': account.accountPassword,
          'url': account.accountUrl,
          'des': account.accountDescription,
          'catalogKey': account.accountCatalog.key().id(),
          'catalogName': account.accountCatalog.catalogName,
          'type':'account'
        }   

    page.response.out.write(json.write(result))

def showCatalog(page):
    catalogKey = page.request.get('key')
    catalog = dbAccess.getCatalog(int(catalogKey))

    result = {
      'key': catalog.key().id(),
      'name': catalog.catalogName,
      'des': catalog.catalogDescription,
      'parentKey': '',
      'parentName': '',
      'type':''
    } 
    if(catalog.catalogParent) :
        result['parentKey'] = catalog.catalogParent.key().id()
        result['parentName'] = catalog.catalogParent.catalogName
        result['type'] = 'catalog'
    else:
        result['type'] = 'root'
        
    logging.info(catalog.catalogName+' '+result['parentName'])
    page.response.out.write(json.write(result))

def newCatalog(page):
    catalogName =  page.request.get('catalog_name')
    catalogDescription =  page.request.get('catalog_des')
    parentKey =  page.request.get('parent_catalog_key')

    newCatalog = CatalogDb(
        catalogName=catalogName,
        catalogDescription = catalogDescription,
        catalogParent=dbAccess.getCatalog(int(parentKey)))
    newCatalogKey = newCatalog.put()

    result = {
        'message':'success'
        }   

    page.response.out.write(json.write(result))

def modifyCatalog(page):
    catalogKey =  page.request.get('catalog_key')
    catalogName =  page.request.get('catalog_name')
    catalogDescription =  page.request.get('catalog_des')
    parentKey =  page.request.get('parent_catalog_key')
    logging.info(catalogDescription);
    catalog = dbAccess.getCatalog(int(catalogKey))
    catalog.catalogName=catalogName
    catalog.catalogDescription=catalogDescription
    catalog.parentKey = parentKey
    catalog.put()

    result = {
        'message':'success'
        }   

    page.response.out.write(json.write(result))

def deleteCatalog(page):
    key =  page.request.get('key')

    dbAccess.deleteCatalog(int(key))

    result = {
         'message':'success',
         'key':key
        }   

    page.response.out.write(json.write(result))
    
def newAccount(page):
    accountName =  page.request.get('account_name')
    accountId =  page.request.get('account_id')
    accountPassword =  page.request.get('account_pwd')
    accountUrl =  page.request.get('account_url')
    accountDescription =  page.request.get('account_des')
    accountCatalogKey =  page.request.get('account_catalog_key')

    newAccount = AccountDb(
        accountName=accountName,
        accountId=accountId,
        accountPassword=accountPassword,
        accountUrl=accountUrl,
        accountDescription=accountDescription,
        accountCatalog=dbAccess.getCatalog(int(accountCatalogKey)))
    newAccount.put()
    result = {
        'message':'success'
        }   

    page.response.out.write(json.write(result))
  
def modifyAccount(page):
    accountKey =  page.request.get('account_key')
    accountName =  page.request.get('account_name')
    accountId =  page.request.get('account_id')
    accountPassword =  page.request.get('account_pwd')
    accountUrl =  page.request.get('account_url')
    accountDescription =  page.request.get('account_des')
    accountCatalogKey =  page.request.get('account_catalog_key')

    account = dbAccess.getAccount(int(accountKey))
    account.accountName=accountName
    account.accountId=accountId
    account.accountPassword=accountPassword
    account.accountUrl=accountUrl
    account.accountDescription=accountDescription
    account.accountCatalog=dbAccess.getCatalog(int(accountCatalogKey))
    account.put()
    result = {
        'message':'success'
        }   

    page.response.out.write(json.write(result))
    
def deleteAccount(page):
    key =  page.request.get('key')
    dbAccess.deleteAccount(int(key))
    result = {
         'message':'success',
         'key':key
        }   
    page.response.out.write(json.write(result))